import { Button, Card, Col, message, Radio, Row, Select } from "antd";
import Form, { WrappedFormUtils } from "antd/lib/form/Form";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { MainCard } from "src/business/components/style-components/main-card";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from 'src/projects/app/appService';
import { isPermission } from "src/projects/app/permission";
import { ROUTE_PATH } from 'src/projects/router';
// Card, Col,
/**
 * 组件：需求记录状态
 */
export interface ChangeRequirementRecordViewState extends ReactViewState {
    /** 基础数据 */
    base_data?: any;
    /** 数据id */
    selete_obj?: object;
    /** 项目列表 */
    project_list?: any[];
    /** 项目列表集合 */
    all_project_list?: any[];
    /** 长者列表 */
    elder_list?: any[];
    /** 模板列表 */
    template_list?: any[];
    /** 模板列表集合 */
    all_template_list?: any[];
    /** 长者 */
    elder?: string;
    /** 模板 */
    template?: string;
}
export interface RequirementRecordFormValues {
    id?: string;
}
/**
 * 组件：需求记录视图
 */
export class ChangeRequirementRecordView extends ReactView<ChangeRequirementRecordViewControl, ChangeRequirementRecordViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            elder_list: [],
            template_list: [],
            project_list: [],
            elder: '',
            template: '',
            all_project_list: [],
            all_template_list: [],
            base_data: {},
        };
    }
    /** 提交方法 */
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: RequirementRecordFormValues) => {
            let project: any[] = [];
            let total_weight = 0;
            for (let id in values) {
                if (id) {
                    this.state.all_project_list!.map((key, value) => {
                        if (id === key.reqirement_project) {
                            key['value'] = values[id];
                            project.push(key);
                        }
                    });
                    if (id !== 'elder' && id !== 'template') {
                        total_weight += parseInt(values[id], undefined);
                    }
                }
            }
            /** 需求记录 */
            let requirement_records: object = {
                elder: values['elder'],
                template: values['template'],
                project_list: project,
                total_weight: total_weight
            };
            if (this.props.match!.params.key) {
                requirement_records['id'] = this.props.match!.params.key;
            }
            AppServiceUtility.requirement_record_service.update_requirement_record!(requirement_records)!
                .then((data) => {
                    if (data) {
                        message.info('保存成功');
                        this.props.history!.push(ROUTE_PATH.requirementRecord);
                    }
                });
        });
    }

    returnBtn = () => {
        this.props.history!.push(ROUTE_PATH.requirementRecord);
    }

    componentDidMount() {
        AppServiceUtility.person_org_manage_service.get_personnel_elder!({})!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        elder_list: data.result
                    });
                }

            });
        AppServiceUtility.requirement_template_service.get_requirement_template_list!({})!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        template_list: data.result,
                        // all_template_list: data.result
                        // elder: data!.result![0].elder,

                    });
                }
            });
        AppServiceUtility.requirement_project_service.get_list!({})!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        project_list: data.result,
                        // elder: data!.result![0].elder,

                    });
                }
            });

        if (this.props.match!.params.key) {
            AppServiceUtility.requirement_template_service.get_requirement_template_list!({ id: this.props.match!.params.key }, 1, 1)!
                .then((data) => {
                    console.info(data);
                    this.setState({
                        base_data: data!.result![0],
                        all_template_list: data!.result![0]['dataSource']
                    });
                });
        }
        // itemOnChange = (value: any, option: any) => {
        //     let list: any[] = this.state.all_project_list!;
        //     AppServiceUtility.requirement_project_service.get_list!({ id: value })!
        //         .then((data: any) => {
        //             if (list.length > 0 && data) {
        //                 list[option.key] = data.result[0];
        //                 this.setState({
        //                     all_project_list: list
        //                 });
        //             }
        //         });
        // }
    }
    /** 入住需求选项改变 */
    itemOnChange = (value: any, option: any) => {
        let list: any[] = this.state.all_project_list!;
        AppServiceUtility.requirement_project_service.get_list!({ id: value })!
            .then((data: any) => {
                if (list.length > 0 && data) {
                    list[option.key] = data.result[0];
                    this.setState({
                        all_project_list: list
                    });
                }
            });
    }
    /** 选择模板选择框值改变 */
    template_change = (value: any) => {
        console.info(value);
        AppServiceUtility.requirement_template_service.get_requirement_template_list!({ id: value }, 1, 10)!
            .then((data: any) => {
                console.info(data);
                if (data.result) {
                    this.setState({
                        all_project_list: data.result[0].dataSource
                        // all_project_list: data.result[0].pro_info
                    });
                }
            });
    }

    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }

        const { getFieldDecorator } = this.props.form!;
        const formItemLayout = {
            labelCol: {
                xs: { span: 18 },
                sm: { span: 2 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 22 },
            },
        };
        let elder = this.state.elder_list!.map((key, value) => {
            return <Select.Option key={key.id}>{key.name}</Select.Option>;
        });
        // let template = this.state.all_template_list!.map((key, value) => {
        //     return <Select.Option key={key.id}>{key.template_name}</Select.Option>;
        // });
        // let project = this.state.all_project_list!.map((key, value) => {
        //     return (
        //         <Form.Item label={value + 1 + '、' + key.project_name} key={key.id}>
        //             {getFieldDecorator('' + key.id, {
        //                 initialValue: key.value ? key.value : '',
        //                 rules: [{
        //                     required: false,
        //                 }],
        //             })(
        //                  key.dataSource!.map((projects: any, index: any) => {
        //                     <Radio.Group>
        //                         {
        //                             projects.requirement_option!.map((option: any, index_op: any) => {
        //                                 console.warn(option);
        //                                 return <p key={index_op}><Radio value={option.weight}>{option.option_name + '，' + option.option_content}</Radio></p>;
        //                             })}  

        //                     </Radio.Group>
        //                 })
        //             )}
        //         </Form.Item>
        //     );

        // });
        let project_list;
        if (this.state.all_project_list!.length > 0) {
            project_list = this.state.all_project_list!.map((value, index) => {
                return (
                    <Card key={index}>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label=''>
                                    {getFieldDecorator('project_name___' + index, {
                                        initialValue: value.project_name ? value.project_name : '',
                                        rules: [{
                                            required: false,
                                            // message: '请选择需求项目'
                                        }],
                                    })(
                                        <Select showSearch={true} key={value.requirement_projects} onChange={this.itemOnChange}>
                                            {this.state.project_list!.map((key) => {
                                                return <Select.Option key={index} value={key['id']}>{key['project_name']}</Select.Option>;
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                                {
                                    value.requirement_options ? value.requirement_options.map((service_options: any, indexs: any) => {
                                        // console.info(value['requirement_options']);
                                        return (
                                            <Form.Item label={indexs + 1 + '、'} key={indexs}>
                                                {getFieldDecorator(service_options.requirement_option_ids + '___' + indexs, {
                                                    initialValue: '',
                                                    rules: [{
                                                        required: false,
                                                    }],
                                                })(
                                                    <Radio.Group>
                                                        {
                                                            service_options.requirement_option.dataSource!.map((item: any, content: any) => {
                                                                return <p key={content}><Radio value={item.weight}>{item.option_content}</Radio></p>;
                                                            })
                                                        }
                                                    </Radio.Group>
                                                )}
                                            </Form.Item>
                                        );
                                    }) : ''
                                }
                            </Col>
                        </Row>
                    </Card>
                );
            });
        }
        return (
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                <MainContent>
                    <MainCard title='需求记录'>
                        <Form.Item label='选择长者'>
                            {getFieldDecorator('elder', {
                                initialValue: this.state.elder ? this.state.elder : '',
                                rules: [{
                                    required: true,
                                    message: '请选择长者'
                                }],
                            })(
                                <Select showSearch={true}>
                                    {elder}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label='选择模板'>
                            {getFieldDecorator('template', {
                                initialValue: this.state.template ? this.state.template : '',
                                rules: [{
                                    required: true,
                                    message: '请选择模板'
                                }],
                            })(
                                <Select showSearch={true} onChange={this.template_change}>
                                    {this.state.template_list!.map((key, index) => {
                                        return <Select.Option key={index} value={key['id']}>{key['template_name']}</Select.Option>;
                                    })}
                                </Select>
                            )}
                        </Form.Item>
                        {project_list}
                    </MainCard>
                </MainContent>
                <Row type='flex' justify='center'>
                    <Button htmlType='submit' type='ghost'>保存</Button>
                    <Button type='ghost' name='返回' htmlType='button'>返回</Button>
                </Row>
            </Form>
        );
    }
}

/**
 * 控件：需求记录控件
 * @description 需求记录控件
 * @author
 */
@addon('ChangeRequirementRecordView', '需求记录控件', '需求记录控件')
@reactControl(Form.create<any>()(ChangeRequirementRecordView), true)
export class ChangeRequirementRecordViewControl extends ReactViewControl {
    form?: WrappedFormUtils<any>;
    /** 视图权限 */
    public permission?: Permission;
}